/**
 * 评论留言模块
 * @author 梁晓东
 */

layui.define(['layer', 'jquery', 'laypage', 'laytpl', 'form', 'face'], function(exports) {


    var $ = layui.jquery,
        layer = layui.layer,
        laytpl = layui.laytpl,
        laypage = layui.laypage,
        faces = layui.face,
        form = layui.form;

    var $dataDom = $('#jieda');
    var arrayGet = new Array();
    arrayGet = getParameter();
    var uid = $('#uid').val();
    var sid = $('#sid').val();
    var username = $('#nickname').val();
    var avater = arrayGet['avater'];
    /*测试数据*/
    //	var sid = 'homework_hid_666';
    //	var uid = 3231;
    //	var username = '梁晓东';
    //	var avater = 'http://p1.pstatp.com/thumb/17800015c3897b28db76';

    $('#sid').val(sid);
    $('#nickname').val(username);
    $('#iconUrl').val(avater);
    $('#uid').val(uid);

    listen_submit();
    //提交评论
    function listen_submit() {
        $('#dosub').click(function() {
            $.ajax({
                url: "/Content/Comment/comment",
                data: $('#fabiao').serialize(),
                type: "POST",
                dataType: "json",
                success: function(ret) {
                    if (ret.status) {
                        layer.msg(ret.info, { icon: 1, time: 1000 }, function() {
                            var info = ret.data;
                            var html = '';
                            var avater = '/Public/res/images/avatar/default.png';
                            if (info.iconurl) {
                                info.iconurl = info.iconurl;
                            }
                            info.content = changeContent(info.content);
                            info.ctime = setTime(info.ctime);
                            var data = new Array();

                            data[0] = info;
                            var dataTpl = $('#comment-tpl').html();
                            laytpl(dataTpl).render(data, function(html) {
                                $dataDom.append(html);
                                listen_sp();
                                listen_reply();
                                listen_aite();
                                listen_fangda();
                                $('#L_content').val('');
                            });
                        });
                    } else {
                        if (ret.info == '用户ID不能为空') {
                            layer.msg('您尚未登录', { time: 1000 }, function() {
                                window.location = '/user/reg.html';
                            });

                        }
                    }
                }
            });
        });

    }


    //加载数据
    function loadData(p, row) {
        var dataUrl = '/Content/Comment/getdata';
        var $datashow = $('#jieda');
        var myCondition = "sid=" + $('#sid').val() + "&uid=" + uid + "&p=" + p + "&row=" + row;
        var $pageDom = $('#comment-page');
        var dataTpl = $('#comment-tpl').html();
        $.ajax({
            url: dataUrl,
            cache: true, //缓存数据
            type: "POST",
            data: myCondition,
            dataType: "json",
            beforeSend: function() {
                ii = layer.msg('Loading...', { icon: 16, time: 10000 });
            },
            complete: function() {
                layer.close(ii);
            },
            success: function(res) {
                if (res.status) {
                    //开始渲染数据
                    console.log(res);
                    var data = res.data.data;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            data[i].content = changeContent(data[i].content);
                            data[i].ctime = setTime(data[i].ctime);
                        }
                        laytpl(dataTpl).render(data, function(html) {
                            $dataDom.html(html);
                            listen_sp();
                            listen_reply();
                            listen_aite();
                            listen_fangda();
                        });
                    }
                    //载入分页
                    if ($pageDom.length != 0) {
                        laypage({
                            cont: $pageDom,
                            pages: Math.ceil(res.data.page.total / res.data.page.row),
                            first: 1,
                            last: Math.ceil(res.data.page.total / res.data.page.row),
                            curr: res.data.page.cur,
                            prev: '上一页',
                            next: '下一页',
                            skip: true,
                            jump: function(obj) {
                                //处理跳转，回调自己（递归）
                                if (obj.curr != p) {
                                    p = obj.curr;
                                    //当前页发生改变的时候执行一下改变
                                    $datashow.attr('data-p', p);
                                    $datashow.attr('data-row', row);

                                    loadData(p, row);
                                }

                            }
                        });
                    }

                } else {
                    layer.msg(res.info, { icon: 2, time: 1000 });
                }
            }
        });
    }

    function changeContent(content) {
        //支持的html标签
        var html = function(end) {
            return new RegExp('\\[' + (end || '') + '(pre|div|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)\\]\\n*', 'g');
        };
        content = escape(content || '') //XSS
            .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
                return '<img data-isbig="0" class="lxd-img" width="200px" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
            }).replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;" class="fly-aite">$1</a>$2') //转义@
            .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
                var alt = face.replace(/^face/g, '');
                return '<img alt="' + alt + '" title="' + alt + '" src="' + faces[alt] + '">';
            }).replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义链接
                var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                if (!href) return str;
                var rel = /^(http(s)*:\/\/)\b(?!(\w+\.)*(sentsin.com|layui.com))\b/.test(href.replace(/\s/g, ''));
                return '<a href="' + href + '" target="_blank"' + (rel ? ' rel="nofollow"' : '') + '>' + (text || href) + '</a>';
            }).replace(html(), '\<$1\>').replace(html('/'), '\</$1\>') //转移代码
            .replace(/\n/g, '<br>') //转义换行   
        return content;
    }


    function escape(html) {
        return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
            .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
    }


    // 获取当前时间戳(以s为单位)
    function setTime(time) {
        var currentTime = Date.parse(new Date());
        var dateTime = time; //后台传递来的时间
        var ts = ''; //选择器
        var d_day = Date.parse(new Date(dateTime));
        var day = Math.abs(parseInt((d_day - currentTime) / 1000 / 3600 / 24)); //计算日期
        var hour = Math.abs(parseInt((d_day - currentTime) / 1000 / 3600)); //计算小时
        var minutes = Math.abs(parseInt((d_day - currentTime) / 1000 / 60)); //计算分钟
        var seconds = Math.abs(parseInt((d_day - currentTime) / 1000)); //计算秒
        if (day >= 2) {
            ts = (parseInt(day) + "天前").toString();
        } else if (day > 0 && day < 2) {
            ts = ("昨天").toString();
        } else if (hour > 0 && hour < 24) {
            ts = (parseInt(hour) + "小时前").toString();
        } else if (minutes > 0 && minutes < 60) {
            ts = (parseInt(minutes) + "分钟前").toString();
        } else if (seconds > 0 && seconds < 60) {
            ts = (parseInt(seconds) + "秒前").toString();
        }
        return ts;
    }

    //赞别人的评论
    function listen_sp() {
        $('.jieda-zan').unbind('click').click(function() {
            var pid = $(this).attr('data-id');
            var $dom = $(this);
            $.post('/Content/Comment/do_ding', { 'cid': pid, 'uid': uid }, function(ret) {
                if (ret.status) {
                    var value = $dom.find('em').text();
                    if ($dom.hasClass('zanok')) {
                        $dom.removeClass('zanok');
                        $dom.find('em').text(parseInt(value - 1));
                    } else {
                        $dom.addClass('zanok');
                        $dom.find('em').text(parseInt(value + 1));
                    }
                    //	                layer.msg(ret.info,{icon:1,time:1000});
                } else {
                    //	                layer.msg(ret.info,{icon:2,time:1000});
                }
            });
        });
    }

    //回复的评论
    function listen_reply() {
        $('.reply').unbind('click').click(function() {
            var isaite = $(this).attr('data-isaite');
            if (isaite == 0) {
                var name = $(this).attr('data-name');
                var value = $('#L_content').val();
                $('#L_content').val(value + '@' + name + ' ');
                $(this).attr('data-isaite', '1');
                $('#L_content').focus();
            }
        });
    }

    //点击艾特查看信息
    function listen_aite() {
        $('.fly-aite').unbind('click').click(function() {
            var name = $(this).html();
            var uid = '';
            $.get("/User/Mynotes/get_uid", { name: name }, function(result) {
                if (result.status) {
                    uid = result.data;
                    window.open("/user/userinfo/index.html?uid=" + uid);
                }
            });


        });
    }

    //图片放大
    function listen_fangda() {
        $('.lxd-img').unbind('click').click(function() {
            var isbig = $(this).attr('data-isbig');
            if (isbig == 1) {
                $(this).css('width', '200px');
                $(this).attr('data-isbig', '0');
            } else {
                $(this).css('width', '400px');
                $(this).attr('data-isbig', '1');
            }
        });
    }

    /**
     * 默认加载数据
     */
    loadData($dataDom.attr('data-p'), $dataDom.attr('data-row'));
    var comment = {
        test: function(t) {
            layer.alert(t);
        }
    };

    function getParameter() {
        var arrays = new Array();
        var query = window.location.search; //获取URL地址中？后的所有字符  
        if (query) {
            var p = query.split('?');
            var param = p[1].split('&');
            for (var i = 0; i < param.length; i++) {
                var a = param[i].split('=');
                arrays[a[0]] = decodeURI(a[1]);
            }
        }
        return arrays;
    }

    exports('comment', comment); //对外接口

});